package utilities;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import javax.swing.JComponent;

import towerDefense.T_Object;
import towerDefense.World;

/**
 * Draws all objects onto the map. Uses the {@link towerDefense.World#getObjects} to find
 * all objects in the world in order to draw them. 
 * 
 * @author Guillermo Mendez-Kestler
 *
 */
public class Painter extends JComponent {
	/**
	 * Serial Version UID Auto Generated. 
	 */
	private static final long serialVersionUID = -6947324759466092360L;
	// declare two instance variables at the head of the program
	private Image dbImage;
	private Graphics dbg; 
	
	/**
	 * Draws all objects in the game space. 
	 */
	public void paintComponent(Graphics g){
		Graphics2D g2 = (Graphics2D) g;
		for(T_Object object: World.getObjects()){
			g2.draw(object.getSpace());
		}
	}
	
	/**
	 * Double buffers the image to prevent flickering. 
	 */
	public void update (Graphics g) {
	       // initialize buffer
	      if (dbImage == null) {
	            dbImage = createImage (this.getSize().width, this.getSize().height);
	            dbg = dbImage.getGraphics ();
	      }

	      // clear screen in background
	      dbg.setColor (getBackground ());
	      dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);

	      // draw elements in background
	      dbg.setColor (getForeground());
	      paint (dbg);

	      // draw image on the screen
	      g.drawImage (dbImage, 0, 0, this); 
	}

}
